package com.sinochem.ubmp.app.utils;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;

import com.facebook.react.modules.upgrade.DownloadService;
import com.sinochem.ubmp.app.R;

import java.io.File;


public class AppUtils {

    public static int getVersionCode(Context mContext) {
        if (mContext != null) {
            try {
                return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }
        return 0;
    }

    public static String getVersionName(Context mContext) {
        if (mContext != null) {
            try {
                return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }

        return "";
    }

    /**
     * Android 安装应用
     *
     * @param context Application Context
     */
    public static void installApk(Context context, File file) {
        if (file.exists()) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            ((ContextWrapper) context).startActivity(i);
        } else {
            Toast.makeText(context, context.getString(R.string.install_fail_file_not_exist), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 安装apk应用
     *
     * @param context
     * @param filePath
     */
    public static void installApk(Context context, String filePath) {
        File _file = new File(filePath);
        if (_file.exists()) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.fromFile(_file), "application/vnd.android.package-archive");
            ((ContextWrapper) context).startActivity(i);
        } else {
            Toast.makeText(context, context.getString(R.string.install_fail_file_not_exist), Toast.LENGTH_SHORT).show();
        }
    }


}
